﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using MRadio.Device;
using System.Threading;
using Microsoft.Xna.Framework;

namespace MRadio
{
    public partial class MainPage : PhoneApplicationPage
    {
        private Tuner tunnerDevice;
        /// <summary>
        /// 指示是否切出应用程序
        /// </summary>
        private bool isReturnApp;
        /// <summary>
        /// 定时器定时检测信号强度
        /// </summary>
        private Timer tmSignalTest;
        private static bool IsShowPopUp = false;
        private bool IsInit = false;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            tunnerDevice = new Tuner();
            tunnerDevice.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(tunnerDevice_PropertyChanged);
            tunnerDevice.NoChannelEvent += new EventHandler(tunnerDevice_NoChannelEvent);
            Global.ChangeFavoriteChanne = new Action<float>((f) =>
            {
                tunnerDevice.Frequency = double.Parse(f.ToString());
            });           
        }
      
        #region -- 页面事件 --

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (isReturnApp)
            {
                tunnerDevice_PropertyChanged(null, null);
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            isReturnApp = true;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult messageBoxResult = MessageBox.Show("Are you sure to exit application and stop the FM radio ?", "CAUTION", MessageBoxButton.OKCancel);
            if (messageBoxResult == MessageBoxResult.OK)
            {
                tunnerDevice.Stop();
                tunnerDevice.StopMedia();
                new Game().Exit();
            }
            else
                e.Cancel = true;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                if (!IsInit)
                {
                    ctlTunner.InitTunner((float)tunnerDevice.Minimum, (float)tunnerDevice.Maximum, (int)tunnerDevice.Region);
                    ctlTunner.TunnerChanged += new Action<MouseVector>(tunner_TunnerChanged);
                    ctlTunner.TunnerChangeComplated += new Action(ctlTunner_TunnerChangeComplated);
                    tunnerDevice.Start();
                    tunnerDevice_PropertyChanged(null, null);
                    tmSignalTest = new Timer(deveiceSingnalTest, null, 0, 500);

                    IsInit = true;
                    //poUserGuid.IsOpen = Global.IsShowUserGuid;
                }
            });
        }

        /// <summary>
        /// 添加到收藏夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddFavorite(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Favorate.xaml?F=" + (float)tunnerDevice.Frequency, UriKind.Relative));
        }

        #endregion

        #region -- 事件处理 --

        /// <summary>
        /// 向前搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RadioScanPrevious(object sender, RoutedEventArgs e)
        {
            tunnerDevice.ScanPrevious();
        }

        /// <summary>
        /// 向后搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RadioScanNext(object sender, RoutedEventArgs e)
        {
            tunnerDevice.ScanNext();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tunnerDevice_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                FMDisplayer.FequenceValue = (float)tunnerDevice.Frequency;
                ctlTunner.CurrentFequences = (float)tunnerDevice.Frequency;
                SignalValueChange = tunnerDevice.SignalStrength;
                tb_channelTitle.Text = Global.GetChannel((float)tunnerDevice.Frequency);
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tunnerDevice_NoChannelEvent(object sender, EventArgs e)
        {
           this.Dispatcher.BeginInvoke(() =>
           {
               MessageBox.Show("There is no channel, please insert your headphone !", "CAUTION", MessageBoxButton.OK);
           });
        }


        /// <summary>
        /// 定时检测信号强度
        /// </summary>
        /// <param name="obj"></param>
        private void deveiceSingnalTest(object obj)
        {
            tunnerDevice_PropertyChanged(null, null);
        }

        /// <summary>
        /// 微调数值改变
        /// </summary>
        /// <param name="obj"></param>
        void tunner_TunnerChanged(MouseVector obj)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                FMDisplayer.FequenceValue = (float)obj.Value;
                tunnerDevice.Frequency = (float)obj.Value;
            });
        }

        /// <summary>
        /// UI界面修改完毕
        /// </summary>
        void ctlTunner_TunnerChangeComplated()
        {
            if (!IsShowPopUp)
            {
                button1.IsEnabled = true;
                button2.IsEnabled = true;
                poUserGuid.IsOpen = Global.IsShowUserGuid;
                IsShowPopUp = true;
            }
            
        }
        /// <summary>
        /// 信号变化
        /// </summary>
        private double SignalValueChange
        {
            #region -- 指示灯变换状态 --
            set
            {
                if (value > 0.25)
                {
                    VisualStateManager.GoToState(ctlSignalLight, "Pressed", false);
                }
                else
                {
                    VisualStateManager.GoToState(ctlSignalLight, "Normal", false);
                }

                if (value > 0.4)
                {
                    VisualStateManager.GoToState(ctlSteroLight, "Pressed", false);
                }
                else
                {
                    VisualStateManager.GoToState(ctlSteroLight, "Normal", false);
                }
            }
            #endregion
        }

        /// <summary>
        /// 暂停或播放按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PauseOrPlayClick(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).Tag.ToString() == "Play")
            {
                tunnerDevice.Start();
                CtlButtonPause.Visibility = Visibility.Visible;
                CtlButtonPlay.Visibility = Visibility.Collapsed;
                btnNext.IsEnabled = true;
                btnPre.IsEnabled = true;

                //VisualStateManager.GoToState(btnNext, "Normal", false);
                //VisualStateManager.GoToState(btnPre, "Normal", false);
                btnNext.ImageSourceNormal = Global.GetImageByName("Button_Pre_Normal.png");
                btnPre.ImageSourceNormal = Global.GetImageByName("Button_Next_Normal.png");
            }
            else
            {
                tunnerDevice.Stop();
                CtlButtonPause.Visibility = Visibility.Collapsed;
                CtlButtonPlay.Visibility = Visibility.Visible;
                btnNext.IsEnabled = false;
                btnPre.IsEnabled = false;

                //VisualStateManager.GoToState(btnNext, "Pressed", false);
                //VisualStateManager.GoToState(btnPre, "Pressed", false);
                btnNext.ImageSourceNormal = Global.GetImageByName("Button_Pre_Pressed.png");
                btnPre.ImageSourceNormal = Global.GetImageByName("Button_Next_Pressed.png");
            }
        }

        #endregion

        #region Show or never show user guid popup
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClosePopUp(object sender, EventArgs e)
        {
            poUserGuid.IsOpen = false;
        }

        private void NeverShowPopUp(object sender, EventArgs e)
        {
            poUserGuid.IsOpen = false;
            Global.IsShowUserGuid = false;
        }
        #endregion
    }
}